// 封装防抖指令
import type { DirectiveBinding } from 'vue'

interface ElType extends HTMLElement {
  HandleClick: () => any
}

export const debounce = (app: any) => {
  app.directive('debounce', {
    mounted(el: ElType, binding: DirectiveBinding) {
      // 先判断类型
      if (typeof binding.value !== 'function') {
        throw '值应该是个函数'
      }

      let timer: any = null
      el.HandleClick = () => {
        if (timer) clearTimeout(timer)

        timer = setTimeout(() => {
          binding.value()
        }, 1000)
      }
      el.addEventListener('click', el.HandleClick)
    },
    beforeUnmount(el: ElType) {
      el.removeEventListener('click', el.HandleClick)
    }
  })
}
